const vscode = require("vscode");
const fs = require('fs');
const path = require('path');
const {
    SetConfigList,
    GetConfigList,
    GetWar3Table,
    UpdateWar3Config,
    run_lua,
    War3Helper,
} = require('./lua');

// 在模块作用域内定义 Webview 视图类
class MapWebviewProvider {
    constructor(context) {
        this._context = context;
        this._htmlContent = ''; // 用于缓存 HTML 内容
        this._currentData = []; // 存储当前展示的数据结构

        // 创建状态栏项
        this.statusBarItem1 = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
        this.statusBarItem1.text = '$(gear) $运行地图';
        this.statusBarItem1.tooltip = '点我运行地图';
        this.statusBarItem1.command = 'war3helper.RunWar3Map';
        this.statusBarItem1.show();
        // 创建状态栏项
        this.statusBarItem33 = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
        this.statusBarItem33.text = '$(gear) $启动魔兽';
        this.statusBarItem33.tooltip = '点我启动一个魔兽';
        this.statusBarItem33.command = 'war3helper.LaunchWar3';
        this.statusBarItem33.show();
        // 创建状态栏项
        this.refreshBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
        this.refreshBarItem.text = '$(sync) $地图导出数据到.build';
        this.refreshBarItem.tooltip = '地图导出到.build';
        this.refreshBarItem.command = 'war3helper.refresh';
        this.refreshBarItem.show();
        // 创建状态栏项
        this.statusBarItem2 = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
        this.statusBarItem2.text = '$(gear) .build合并数据成地图';
        this.statusBarItem2.tooltip = '点我把.build文件夹合并成地图';
        this.statusBarItem2.command = 'war3helper.MergeBuild';
        this.statusBarItem2.show();
        // 创建状态栏项
        this.statusBarItem3 = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
        this.statusBarItem3.text = '$(gear) $生成发布版';
        this.statusBarItem3.tooltip = '点我生成发布版地图，合并【虚拟MPQ、每次预加载文件、物编】所有数据';
        this.statusBarItem3.command = 'war3helper.SlkMap';
        this.statusBarItem3.show();
        // 创建状态栏项
        this.statusBarItem4 = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
        this.statusBarItem4.text = '$(gear) $拉取WPS表格';
        this.statusBarItem4.tooltip = '点我拉取WPS表格';
        this.statusBarItem4.command = 'war3helper.WPSClone';
        this.statusBarItem4.show();
        // 创建状态栏项
        this.statusBarItem5 = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
        this.statusBarItem5.text = '$(gear) $单位表格导出到w3u';
        this.statusBarItem5.tooltip = '点我导出单位表格';
        this.statusBarItem5.command = 'war3helper.OutUnitXlsx';
        this.statusBarItem5.show();
        // 创建状态栏项
        this.statusBarItem6 = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
        this.statusBarItem6.text = '$(gear) $w3u转换为单位表格';
        this.statusBarItem6.tooltip = '点我生成单位表格';
        this.statusBarItem6.command = 'war3helper.SaveUnitXlsx';
        this.statusBarItem6.show();

        this.updateConfig();
    }

    resolveWebviewView(webviewView) {
        this._webviewView = webviewView;
        webviewView.webview.options = {
            enableScripts: true,
            localResourceRoots: [this._context.extensionUri]
        };

        // 监听消息
        webviewView.webview.onDidReceiveMessage(async (message) => {
            console.log(message);
            await this._handleWebviewMessage(message);
        });

        this.update();
    }

    async updateConfig() {
        if (vscode.workspace.getConfiguration().get("war3helper.RunWar3Map")) {
            this.statusBarItem1.show();
        } else {
            this.statusBarItem1.hide();
        }
        if (vscode.workspace.getConfiguration().get("war3helper.LaunchWar3")) {
            this.statusBarItem33.show();
        } else {
            this.statusBarItem33.hide();
        }
        if (vscode.workspace.getConfiguration().get("war3helper.refresh")) {
            this.refreshBarItem.show();
        } else {
            this.refreshBarItem.hide();
        }
        if (vscode.workspace.getConfiguration().get("war3helper.MergeBuild")) {
            this.statusBarItem2.show();
        } else {
            this.statusBarItem2.hide();
        }
        if (vscode.workspace.getConfiguration().get("war3helper.SlkMap")) {
            this.statusBarItem3.show();
        } else {
            this.statusBarItem3.hide();
        }
        if (vscode.workspace.getConfiguration().get("war3helper.WPSClone")) {
            this.statusBarItem4.show();
        } else {
            this.statusBarItem4.hide();
        }
        if (vscode.workspace.getConfiguration().get("war3helper.OutUnitXlsx")) {
            this.statusBarItem5.show();
        } else {
            this.statusBarItem5.hide();
        }
        if (vscode.workspace.getConfiguration().get("war3helper.SaveUnitXlsx")) {
            this.statusBarItem6.show();
        } else {
            this.statusBarItem6.hide();
        }

        if (!(await GetConfigList('MapPath'))) {
            return;
        }
        await run_lua(path.join(path.dirname(__dirname), 'src\\War3Registry.lua'))
        let Platform = await GetConfigList("平台环境")
        if (Platform == null) {
            Platform = '无'
            SetConfigList("平台环境", Platform)
        }
        else {
            await UpdateWar3Config()
        }
    }

    // 刷新数据（模拟原有 TreeDataProvider 的数据获取）
    async refreshData() {
        const currentData = [];
        const workspaceFolder = vscode.workspace.workspaceFolders[0].uri.fsPath;
        const War3Config = (await GetWar3Table('War3Config.json')) ?? {};
        const MapInfo = await GetWar3Table('MapInfo.json');

        const MapPath = War3Config['MapPath'] ?? "未选择地图文件";
        const UnitXlsxPath = War3Config['单位物编表格'] ?? "未配置xlsx表格路径"
        let GamePath;
        if (War3Config['War3Registry']) {
            GamePath = War3Config['War3Registry']["GamePath"]
        }

        if (MapInfo) {
            currentData.push({
                label: path.basename(MapPath),
                icon: "folder-icon-selected.png",
                children: [
                    { label: '地图版本:' + MapInfo["MapVersion"], icon: "map_info.png", buttons: [{ tooltip: "修改", command: "修改-地图版本" }], },
                    { label: '地图名字:' + MapInfo["MapName"], icon: "map_info.png", buttons: [{ tooltip: "修改", command: "修改-地图名字" }], },
                    { label: '地图作者:' + MapInfo["MapAuthor"], icon: "map_info.png", buttons: [{ tooltip: "修改", command: "修改-地图作者" }] },
                    { label: '载入图路径:' + MapInfo["LoadingScreenPath"], icon: "map_info.png", buttons: [{ tooltip: "修改", command: "修改-载入图路径" }] },
                ],
            })
            currentData.push({
                label: "物编数据",
                icon: "folder-icon-selected.png",
                children: [
                    { label: "物品模板", buttons: [{ tooltip: "配置物编", command: "物品模板" }], icon: "map_info.png" },
                ],
            },)
        }
        currentData.push({
            label: "地图路径:" + MapPath,
            icon: "file-icon-selected.png",
            buttons: [
                {
                    tooltip: "选择地图",
                    command: "选择地图文件",
                }
            ],
            children: [
                { label: "本地玩家名:" + War3Config["LocalUserName"], buttons: [{ tooltip: "修改玩家名", command: "修改玩家名" }], icon: "wc3_victoryscreen_difficulty_normal.png" },
                { label: "虚拟MPQ路径", buttons: [{ tooltip: "配置MPQ", command: "虚拟MPQ" }], icon: "ums-map-icon-disabled.png" },
                { label: "云脚本路径:" + (War3Config['Scriptrunner'] ?? '未配置'), buttons: [{ tooltip: "选择路径", command: "云脚本" }], icon: "ums-map-icon-disabled.png" },
                { label: "War3路径:" + (GamePath ?? '未配置'), checkbox: true, buttons: [{ tooltip: "选择路径", command: "War3路径" }], checked: GamePath != null },
                { label: "平台环境:" + (War3Config["平台环境"] ?? '无'), buttons: [{ tooltip: "选择环境", command: "平台环境" }], icon: 'wc3_victoryscreen_difficulty_normal.png' },
                { label: "窗口锁定鼠标", checkbox: true, buttons: [{ tooltip: "开关", command: "游戏运行配置", arg: 'OpenLockMouse' }], checked: War3Config["窗口锁定鼠标"] },
                { label: "固定窗口比例", checkbox: true, buttons: [{ tooltip: "开关", command: "游戏运行配置", arg: 'OpenFixedRatioWindowed' }], checked: War3Config["固定窗口比例"] },
                { label: "窗口化", checkbox: true, buttons: [{ tooltip: "开关", command: "游戏运行配置", arg: 'OpenWar3Window' }], checked: War3Config["窗口化"] },
                { label: "宽屏模式", checkbox: true, buttons: [{ tooltip: "开关", command: "游戏运行配置", arg: 'OpenWideScreen' }], checked: War3Config["宽屏模式"] },
                { label: "OpenGL", checkbox: true, buttons: [{ tooltip: "开关", command: "游戏运行配置", arg: 'OpenWar3OpenGL' }], checked: War3Config["OpenGL"] },
                { label: "多人模式", checkbox: true, buttons: [{ tooltip: "开关", command: "游戏运行配置", arg: 'OpenAutoStartGame' }], checked: War3Config["多人模式"] },
                { label: "Japi环境", checkbox: true, buttons: [{ tooltip: "开关", command: "游戏运行配置", arg: 'OpenYDWEJapi' }], checked: War3Config["Japi环境"] },
            ]
        })
        currentData.push({
            label: "地图项目参数",
            icon: "folder-icon-selected.png",
            children: [
                { label: "自定义配置", buttons: [{ tooltip: "配置", command: "自定义配置" }], icon: "ums-map-icon-disabled.png" },
                { label: "WPS表格配置", buttons: [{ tooltip: "配置表格", command: "WPS表格" }], icon: "ums-map-icon-disabled.png" },
                { label: "每次运行需要添加的文件", buttons: [{ tooltip: "配置路径", command: "预加载文件路径" }], icon: "ums-map-icon-disabled.png" },
                { label: "CLuaPackagePath:" + (War3Config["CLuaPackagePath"] ?? "未配置"), buttons: [{ tooltip: "配置路径", command: "CLuaPackagePath" }], icon: "ums-map-icon-disabled.png" },
                { label: "单位表格路径:" + UnitXlsxPath, buttons: [{ tooltip: "配置路径", command: "单位物编表格路径" }], icon: "ums-map-icon-disabled.png" },
                { label: "发布版使用Luac", checkbox: true, buttons: [{ tooltip: "开关", command: "游戏运行配置", arg: 'OpenBuildLuac' }], checked: War3Config["BuildLuac"] },
                { label: "发布版使用Slk", checkbox: true, buttons: [{ tooltip: "开关", command: "游戏运行配置", arg: 'OpenBuildSlk' }], checked: War3Config["BuildSlk"] },
                { label: "发布版使用KKWE加密", checkbox: true, buttons: [{ tooltip: "开关", command: "游戏运行配置", arg: 'OpenEncodeKKWEJass' }], checked: War3Config["EncodeKKWEJass"] },
            ],
        })
        const PluginScripts1 = {
            label: "运行地图前执行",
            icon: "folder-icon-selected.png",
            buttons: [
                {
                    tooltip: "新增脚本",
                    command: "新增脚本",
                    arg: "运行地图前执行"
                },
            ],
            children: []
        }
        const PluginScripts2 = {
            label: "生成发布版前执行",
            icon: "folder-icon-selected.png",
            buttons: [
                {
                    tooltip: "新增脚本",
                    command: "新增脚本",
                    arg: "生成发布版前执行"
                },
            ],
            children: []
        }
        const PluginScripts3 = {
            label: "生成发布版后执行",
            icon: "folder-icon-selected.png",
            buttons: [
                {
                    tooltip: "新增脚本",
                    command: "新增脚本",
                    arg: "生成发布版后执行"
                },
            ],
            children: []
        }
        let Scripts = (War3Config['PluginScripts']) ?? []
        let NewScripts = []
        for (let i = 0; i < Scripts.length; i++) {
            var script = Scripts[i];
            var f_path = path.join(workspaceFolder, ".tools", script['name'] + ".lua")
            if (await fs.existsSync(f_path)) {
                NewScripts.push(script)
            }
        }
        if (NewScripts.length != Scripts.length) {
            await SetConfigList('PluginScripts', NewScripts)
        }
        NewScripts.map(async (script) => {
            let data = {
                label: script['name'],
                checkbox: true,
                draggable: true,
                scriptType: script['type'],
                checked: script['enable'] == true,
                clicked: {
                    tooltip: "打开",
                    command: "打开插件脚本",
                    arg: script['name']
                },
                buttons: [
                    {
                        tooltip: "启/禁",
                        command: "开关插件脚本",
                        arg: script['type'] + ":" + script['name']
                    },
                    {
                        tooltip: "删除",
                        command: "删除插件脚本",
                        arg: script['type'] + ":" + script['name']
                    },
                ],
                icon: "file-icon-selected.png",
            };

            if (script['type'] == PluginScripts1.label) {
                PluginScripts1.children.push(data)
            } else if (script['type'] == PluginScripts2.label) {
                PluginScripts2.children.push(data)
            } else {
                PluginScripts3.children.push(data)
            }
        });
        currentData.push({
            label: "插件脚本",
            icon: "folder-icon-selected.png",
            children: [
                PluginScripts1,
                PluginScripts2,
                PluginScripts3,
            ],
        })

        return currentData;
    }


    async _updatePluginScriptOrder(order) {
        await SetConfigList('PluginScripts', order);
    }

    // 处理消息
    async _handleWebviewMessage(message) {
        switch (message.command) {
            case 'updatePluginScriptOrder':
                await this._updatePluginScriptOrder(message.order);
                break;
            case '选择地图文件':
                await vscode.commands.executeCommand('war3helper.openMapPath');
                break;
            case '新增脚本':
                await vscode.commands.executeCommand('war3helper.AddPluginScript', message.arg);
                break;
            case '打开插件脚本':
                await vscode.commands.executeCommand('war3helper.OpenPluginScript', message.arg);
                break;
            case '删除插件脚本':
                await vscode.commands.executeCommand('war3helper.RemovePluginScript', message.arg);
                break;
            case '开关插件脚本':
                await vscode.commands.executeCommand('war3helper.EnablePluginScript', message.arg);
                break;
            case '修改玩家名':
                await vscode.commands.executeCommand('war3helper.SetLocalName');
                break;
            case '修改-地图版本':
                await vscode.commands.executeCommand('war3helper.MapVersion');
                break;
            case '修改-地图名字':
                await vscode.commands.executeCommand('war3helper.MapName');
                break;
            case '修改-地图作者':
                await vscode.commands.executeCommand('war3helper.MapAuthor');
                break;
            case '修改-载入图路径':
                await vscode.commands.executeCommand('war3helper.LoadingScreenPath');
                break;
            case '虚拟MPQ':
                await vscode.commands.executeCommand('war3helper.openVirtualPath', '虚拟MPQ');
                break;
            case '云脚本':
                await vscode.commands.executeCommand('war3helper.openScriptrunner');
                break;
            case '预加载文件路径':
                await vscode.commands.executeCommand('war3helper.openLoadPath', '预加载文件路径');
                break;
            case '自定义配置':
                await vscode.commands.executeCommand('war3helper.openCustomConfig', '自定义配置');
                break;
            case 'WPS表格':
                await vscode.commands.executeCommand('war3helper.openWPSConfig', 'WPS表格');
                break;
            case 'War3路径':
                await vscode.commands.executeCommand('war3helper.selectWar3')
                break;
            case '单位物编表格路径':
                await vscode.commands.executeCommand('war3helper.UnitXlsxPath')
                break;
            case 'CLuaPackagePath':
                await vscode.commands.executeCommand('war3helper.CLuaPackagePath')
                break;
            case '平台环境':
                await vscode.commands.executeCommand('war3helper.selectPlatform')
                break;
            case '物品模板':
                await vscode.commands.executeCommand('war3helper.openWar3TableTemplate', '物品物编模板')
                break;
            case '游戏运行配置':
                await vscode.commands.executeCommand('war3helper.' + message.arg)
                break;
            default:
                console.log('未处理的命令', message.command)
                break;
        }
        this.update()
    }

    async update() {
        if (!this._webviewView) return;

        this._currentData = await this.refreshData();
        this._webviewView.webview.html = this._generateHTML();
    }

    // 生成 HTML 结构
    _generateHTML() {
        const styles = `
       <style>
        /* 重置默认样式 */
        body {
            margin: 0;
            padding: 3px;
            font-family:rgb(241, 241, 241);
            font-size: 10px;
            line-height: 1;
            color: rgb(230, 230, 230);
            background-color: rgb(29, 29, 29); /* 添加这一行 */
        }

        /* 树形容器 */
        .tree-container {
            width: 100%;
            max-width: 800px;
            margin: 0 auto;
            text-align: left;
        }

        /* 树形条目 */
        .tree-item {
            padding: 1px 0;
            margin-left: -20px;
            font-size: 1.1em;
        }

        /* 标签容器 */
        .item-label {
            display: flex;
            align-items: center;
            padding: 1px 4px;
            transition: background 0.1s;
            border-radius: 3px;
            cursor: pointer;
        }
        
        /* 鼠标悬停时的高亮效果 */
        .item-label:hover {
            background-color: var(--vscode-list-hoverBackground); /* 使用VSCode的主题色 */
        }

        /* 图标样式 */
        .item-icon {
            width: 10px;
            height: 10px;
            margin-right: 4px;
        }

        /* 文本标签 */
        .item-text {
            flex: 1;
            min-width: 0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin: 0 3px;
        }

        /* 操作按钮 */
        .action-button {
            width: 60px;
            height: 25px;
            padding: 0;
            border: none;
            background: transparent;
            cursor: pointer;
            background-size: cover;
            background-image: url(${this._webviewView.webview.asWebviewUri(
            vscode.Uri.file(path.join(this._context.extensionPath, 'images', 'war3_btn_small_blue_normal_4k.png'))
        )});
            transition: filter 0.1s;
            position: relative;
            color: #ffd700; /* 金色文字 */
            font-weight: bold;
            text-shadow: 1px 1px 2px #000;
            image-rendering: crisp-edges; /* 保持像素风格 */
            background-size: 100% 100%;
        }

        .action-button:disabled {
            filter: grayscale(0.8);
            opacity: 0.7;
            cursor: not-allowed;
            background-image: url(${this._webviewView.webview.asWebviewUri(
            vscode.Uri.file(path.join(this._context.extensionPath, 'images', 'war3_btn_small_disabled_4k.png'))
        )});
        }

        .action-button:hover {
            background-image: url(${this._webviewView.webview.asWebviewUri(
            vscode.Uri.file(path.join(this._context.extensionPath, 'images', 'war3_btn_small_blue_hover_4k.png'))
        )});
            filter: brightness(1.1);
        }

        .action-button:active {
            background-image: url(${this._webviewView.webview.asWebviewUri(
            vscode.Uri.file(path.join(this._context.extensionPath, 'images', 'war3_btn_small_blue_pressed_4k.png'))
        )});
            transform: translateY(1px);
        }

        /* 隐藏原生按钮文字（如需保留文字需调整位置） */
        .action-button > span {
            display: none;
        }

        /* 使用伪元素显示按钮文字 */
        .action-button::after {
            content: attr(data-text);
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            pointer-events: none;
            white-space: nowrap; /* 强制不换行 */
            max-width: 90%; /* 留出边距 */
            font-size: 9px; /* 悬停时略微放大 */
            padding: 0 2px; /* 增加内边距 */
            text-align: center;
            transition: 
                font-size 0.1s ease,
                color 0.1s ease;
        }
        .action-button:hover::after {
            font-size: 11px;
            max-width: 95%;
        }
        /* 复选框图标 */
        .checkbox-icon {
            width: 16px;
            height: 16px;
            margin-right: 6px;
        }
        </style>
      `;

        const scripts = `
        <script>
            const vscode = acquireVsCodeApi();
            function handleCommand(command, arg) {
                vscode.postMessage({ command, arg });
            }

            let draggedItem = null;
          
            // 开始拖拽
            function handleDragStart(event) {
                draggedItem = event.target;
                event.dataTransfer.setData('text/plain', event.target.innerText);
                event.target.style.opacity = '0.4';
            }

            // 拖拽经过
            function handleDragOver(event) {
                event.preventDefault();
                const target = event.target.closest('.tree-item');
                if (target && target !== draggedItem) {
                    // 获取拖拽元素和目标元素的类型
                    const draggedType = draggedItem.getAttribute('data-type');
                    const targetType = target.getAttribute('data-type');
                    
                    // 只有类型一致时才允许拖拽
                    if (draggedType === targetType) {
                        const rect = target.getBoundingClientRect();
                        const offset = event.clientY - rect.top;
                        if (offset < rect.height / 2) {
                            target.parentNode.insertBefore(draggedItem, target);
                        } else {
                            target.parentNode.insertBefore(draggedItem, target.nextSibling);
                        }
                    }
                }
            }

            // 拖拽结束
            function handleDrop(event) {
                event.preventDefault();
                if (draggedItem) {
                    draggedItem.style.opacity = '1';
                    draggedItem = null;
                    // 发送消息通知 VSCode 更新顺序
                    const items = Array.from(document.querySelectorAll('.tree-item[data-plugin-script="true"]'));
                    const order = items.map(item => {
                        const name = item.querySelector('.item-text').innerText;
                        const type = item.getAttribute('data-type');
                        const enable = item.getAttribute('data-enable') == "true";
                        return { type, name, enable };
                    });
                    vscode.postMessage({ command: 'updatePluginScriptOrder', order: order });
                }
            }
        </script>
      `;

        const body = `
        <body>
          <ul>
            ${this._currentData.map(item => this._renderItem(item)).join('')}
          </ul>
          ${styles}
          ${scripts}
        </body>
      `;

        return `<!DOCTYPE html><html>${body}</html>`;
    }

    // 渲染单个条目
    _renderItem(item) {
        const iconPath = item.icon
            ? this._webviewView.webview.asWebviewUri(
                vscode.Uri.file(path.join(this._context.extensionPath, 'images', item.icon))
            )
            : '';


        const onclick = item.clicked ? `
            onclick="handleCommand('${item.clicked.command}', '${item.clicked.arg}')"
        ` : ''

        const checkBox = item.checkbox ? ` <img class="checkbox-icon" 
             src="${this._webviewView.webview.asWebviewUri(
            vscode.Uri.file(path.join(
                this._context.extensionPath,
                'images',
                item.checked ? 'win.png' : 'loss.png'
            ))
        )}">
        ` : "";

        // 添加 draggable 属性
        const draggable = item.draggable ? `
            draggable="true" 
            ondragstart="handleDragStart(event)"
            ondragover="handleDragOver(event)"
            ondrop="handleDrop(event)"
            data-type="${item.scriptType}"
            data-plugin-script="true"
            data-enable="${item.checked}"
        ` : '';

        return `
        <li class="tree-item" ${draggable}>
        <div class="item-label" ${onclick}>
            ${checkBox}
            ${iconPath ? `<img class="item-icon" src="${iconPath}" />` : ''}
            <span class="item-text">${item.label}</span>
            <div class="item-actions">
            ${item.buttons ? item.buttons.map(btn => `
                <button class="action-button" 
                        data-text="${btn.tooltip}"
                        onclick="handleCommand('${btn.command}'${btn.arg ? `, '${btn.arg}'` : ''})"
                        title="${btn.tooltip}">
                    <span>${btn.tooltip}</span>
                </button>
            `).join('') : ''}
            </div>
        </div>
        ${item.children?.length ? `
            <ul>
            ${item.children.map(child => this._renderItem(child)).join('')}
            </ul>
        ` : ''}
        </li>
      `;
    }
}

module.exports = MapWebviewProvider;
